﻿using System;
using System.Net;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Threading;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Collections.Generic;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using Common.Library;
using OnlineVideos.Common;
using System.Windows.Threading;
using OnlineVideos.Library;
//using SyncStories;
using System.IO.IsolatedStorage;
//using OnlineVideos.Data.Tables;
using OnlineVideos.Data;
//using AdRotator;
using System.Linq;
using Windows.Storage;
using System.Threading.Tasks;
using OnlineVideos.Entities;
using System.Windows.Controls.Primitives;
using SyncStories;
using Common.Utilities;
using OnlineVideos;

namespace OnlineVideos
{
    public partial class App : Application
    {
        #region Initialization
        public static dynamic group = default(dynamic);
        public static dynamic grouptelugu = default(dynamic);
        public static ShowList webinfo = default(ShowList);
        public static WebInformation webinfotable = new WebInformation();
        AppInitialize objCustomSetting;
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        DispatcherTimer timer;
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        public static bool AdStatus = false;
       
        public App()
        {          
            UnhandledException += Application_UnhandledException;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Application.Current.Host.Settings.EnableFrameRateCounter = true;
            }

            //RootFrame.UriMapper = Resources["UriMapper"] as UriMapper;

            AppSettings.NavigationID = false;

            objCustomSetting = new AppInitialize();
            timer = new DispatcherTimer();
            Constants.DownloadTimer = timer;
            InitializeComponent();

            InitializePhoneApplication();
        }

        #endregion

        #region "Private Methods"

        void StartDownloadingShows()
        {
            timer.Interval = TimeSpan.FromSeconds(10);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
        void timer_Tick(object sender, EventArgs e)
        {
            try
            {
              BackgroundWorker worker = new BackgroundWorker();
              worker.DoWork += new DoWorkEventHandler(StartBackgroundDownload);
              worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
              worker.RunWorkerAsync();
            }
            catch (Exception)
            {
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (AppSettings.StopTimer == "True")
            {
                timer.Stop();
                AppSettings.StopTimer = "False";
            }
        }

       async void StartBackgroundDownload(object sender, DoWorkEventArgs e)
        {
            //AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
             switch (AppSettings.BackgroundAgentStatus)
            {
                case SyncAgentStatus.DownloadFavourites:
                    if (AppSettings.DownloadFavCompleted == false && AppSettings.SkyDriveLogin == true)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            timer.Stop();
                        });
                        ReStoreFavourites reStoreFav = new ReStoreFavourites();
                        await reStoreFav.RestorefavFolder(ResourceHelper.ProjectName);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadFavourites;
                            timer.Start();
                        });
                    }
                    else
                        AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadFavourites;
                    break;
                case SyncAgentStatus.UploadFavourites:
                    bool result = Task.Run(async () => await Storage.FavouriteFileExists("Favourites.xml")).Result;
                    if (AppSettings.SkyDriveLogin == true && result)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            timer.Stop();
                        });
                        UploadFavourites upLoad = new UploadFavourites();
                        await upLoad.CreateFolderForFav(ResourceHelper.ProjectName);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                            timer.Start();
                        });
                    }
                    else
                        AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadParentalControlPreferences;
                    break;

                 case SyncAgentStatus.RestoreStory:
            if (AppSettings.DownloadStoryCompleted == false && AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {

                            timer.Stop();
                        });
                        RestoreStory restore = new RestoreStory();
                        //if (ResourceHelper.ProjectName == "Story Time")
                            await restore.RestoreFolder("StoryRecordings");
                        //else
                        //    await restore.RestoreFolder("VedicRecordings");

                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadStory;
                            timer.Start();

                        });
                    }
                    else
                        AppSettings.BackgroundAgentStatus = SyncAgentStatus.UploadStory;
                    break;
                case SyncAgentStatus.UploadStory:
                    if (AppSettings.SkyDriveLogin == true && (ResourceHelper.ProjectName == "Story Time" || ResourceHelper.ProjectName == "Vedic Library"))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            timer.Stop();
                        });
                        UploadStory st = new UploadStory();
                        //if (ResourceHelper.ProjectName == "Story Time")
                        await st.CreateFolder("StoryRecordings");
                        //else
                        //    await st.CreateFolder("VedicRecordings");
                            
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
                            timer.Start();
                        });
                    }
                    else
                        AppSettings.BackgroundAgentStatus = SyncAgentStatus.DownloadFavourites;
                    break;
                 default:
                    ShowDownloader.StartBackgroundDownload(timer);
                    break;
            }
        }

        #endregion

        #region "Application Events"
        private void pop_Opened_1(object sender, EventArgs e)
        {
            DispatcherTimer timer1 = new DispatcherTimer();
            timer1.Interval = TimeSpan.FromSeconds(5);
            timer1.Tick += timer1_Tick;
            timer1.Start();
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            (sender as DispatcherTimer).Stop();
            Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
            Popup Adc = frameBorder.FindName("pop") as Popup;
            Adc.IsOpen = false;
        }
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {            
            SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(Constants.DataBaseConnectionstringForSqlite);
            Constants.connection = conn;
            AppSettings.AppStatus = ApplicationStatus.Launching;
            AppSettings.StopTimer = "False";
            objCustomSetting.CheckElementSection();
            SyncButton.Login();
            if (AppSettings.IsNewVersion == true)
            {
                AppSettings.RatingUserName = AppResources.RatingUserName;
                AppSettings.RatingPassword = AppResources.RatingPassword;
                AppSettings.ShowsRatingBlogUrl = AppResources.ShowsRatingBlogUrl;
                if (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString())
                AppSettings.QuizRatingBlogUrl = AppResources.QuizRatingBlogUrl;
                AppSettings.LinksRatingBlogUrl = AppResources.LinksRatingBlogUrl;
                AppSettings.ShowsRatingBlogName = AppResources.ShowsRatingBlogName;
                AppSettings.LinksRatingBlogName = AppResources.LinksRatingBlogName;
                if (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString())
                AppSettings.QuizLinksRatingBlogName = AppResources.QuizLinksRatingBlogName;
            }
          Constants.UIThread = true;
          group=OnlineShow.GetTopRatedShows().Items;
          grouptelugu = OnlineShow.GetRecentlyAddedShows().Items;
          Constants.UIThread = false;
           //FlurryWP8SDK.Api.SetSessionContinueSeconds(3600);
           // FlurryWP8SDK.Api.StartSession(AppResources.FlurryAppID);
           // WZR3WKFX7QTTG6JR62Y4
            //AppSettings.lastDownloadedRatingDate = new DateTime(2013, 10, 20);
            //AppSettings.lastVideoDownloadedRatingDate = new DateTime(2013, 10, 20);
            //AppSettings.DownloadCompletedDate = new DateTime(2013, 12, 14);
            //AppSettings.LastUploadRatingId = 0;
         //AppSettings.BackgroundAgentStatus = SyncAgentStatus.UpDateLiveTile;
         //AppSettings.StoryUploadedDate = new DateTime(2013, 9, 11);
           //AppSettings.LastUploadedShowIdHid = 0;
           //AppSettings.LastUploadedVideoIdHid = 0;
           //AppSettings.LastUpdatedDateForHide = "24/2/2013";
         StartDownloadingShows();
        }

        private void Application_Activated(object sender, ActivatedEventArgs e)
        {          
            //FlurryWP8SDK.Api.EndTimedEvent(AppSettings.Title);
            //FlurryWP8SDK.Api.SetSessionContinueSeconds(3600);
            //FlurryWP8SDK.Api.EndTimedEvent(AppSettings.Title);
            //FlurryWP8SDK.Api.StartSession(AppResources.FlurryAppID);
          //WZR3WKFX7QTTG6JR62Y4
            AppSettings.AppStatus = ApplicationStatus.Active;
            
            if (ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString())
            {
                AppSettings.ShowAdControl = false;
            }
        }

        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {          
            AppSettings.AppStatus = ApplicationStatus.Deactive;
            AppState.RingtoneStatus = "TombStoned";
        }

        private void Application_Closing(object sender, ClosingEventArgs e)
        {            
            AppSettings.AppStatus = ApplicationStatus.Closing;
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            FlurryWP8SDK.Api.LogError("Error at Application_UnhandledException in App.xaml.cs", e.ExceptionObject.InnerException);
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            else
            {
                Exceptions.SaveOrSendExceptions("Exception in Application_UnhandledException Method In App.xaml.cs file.", e.ExceptionObject);
                e.Handled = true;
                return;
            }
        }

        #endregion
        
        #region Phone application initialization

        public PhoneApplicationFrame RootFrame { get; private set; }

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;
            
            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.

            RootFrame = new PhoneApplicationFrame();
            if (App.Current.Resources["AdVisible"] as string == "True")
            {
                RootFrame.Style = App.Current.Resources["RootFrameStyle"] as Style;
                RootFrame.ApplyTemplate();
            }
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;

            //NonLinearNavigationService.Instance.Initialize(RootFrame);
        }

        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            else
            {
                Exceptions.SaveOrSendExceptions("Exception in RootFrame_NavigationFailed Method In App.xaml.cs file.", e.Exception);
                e.Handled = true;
                return;
            }
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}